package com.by.controller;

import com.by.auto.token.TokenTemplate;
import com.by.bean.LoginBean;
import com.by.bean.User;
import com.by.common.bean.ResultBean;
import com.by.common.web.controller.BaseController;
import com.by.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sys")
@Api(tags = "用户管理")
@Slf4j
public class UserController extends BaseController {


    @Autowired
    TokenTemplate tokenTemplate;

    @Autowired
    UserService userService;

    @ApiOperation("保存用户")
    @PostMapping("/user")
    public ResultBean save(@RequestBody User user) {
        int rs = userService.saveEntity(user);
        log.info("保存用户的结果:" + rs);
        return saveResult(rs);
    }


    @GetMapping("/user")
    public ResultBean get(HttpServletRequest request){
        String id=request.getHeader("id");
        String username=request.getHeader("username");
        return success("查询信息",username);
    }


    @PostMapping("/login")
    public ResultBean login(@Validated @RequestBody LoginBean bean, BindingResult result) {
        validate(result);
        User user = userService.queryByUserName(bean.getUsername());
        if (null == user)
            return fail("账号不存在!");
        //判断密码
        if (!bean.getPassword().equals(user.getPassword()))
            return fail("用户名或密码错误");

        Map map = new HashMap();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        String token = tokenTemplate.generateToken(map);
        map.put("token", token);
        return success("登录成功", map);
    }

}
